package com.music.mysongs.fragment.main

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.music.mysongs.R
import com.music.mysongs.activity.SongActivity
import com.music.mysongs.adapter.CommonRecyclerAdapter
import com.music.mysongs.web.CommonWebTask
import com.music.mysongs.bean.SongBean
import com.music.mysongs.utils.myLog
import com.music.mysongs.utils.myToast
import com.music.mysongs.bean.BeanManager
import com.music.mysongs.data.*
import com.music.mysongs.file.FileOP
import com.music.mysongs.helper.myActReadIntSPF
import kotlinx.android.synthetic.main.item_recycler_list.view.*
import kotlin.collections.ArrayList

class MusicChildFragment(mList: String) : Fragment() {
    private val mTAG = "MusicChildFragment"
    private val tabName = mList
    private val codeDB = 100
    private val codeColl = 200

    private val beanManager = BeanManager()
    private var beanArr = ArrayList<SongBean>()
    private var musicCollectData: ArrayList<MusicCreatorData.MusicList>? = null

    private var arrRecyclerView: RecyclerView? = null
    private val arrHandler: Handler = Handler {
        when (it.what) {
            codeDB -> {
                arrRecyclerView!!.adapter = CommonRecyclerAdapter.Builder()
                    .setData(beanArr).setLayout(R.layout.item_recycler_list)
                    .bindView { holder, innerData, position ->
                        val bean = innerData as SongBean
                        if (beanArr.size == 0) {
                            myToast(requireContext(), "曲库空空如也")
                        }
                        holder.itemView.txtScanTitle_item.text = bean.title
                        holder.itemView.txtScanArtist_item.text = bean.artist
                        holder.itemView.txtScanTitle_item.setOnClickListener {
                            //myLog("$mTAG: position=$position")
                            Intent(activity, SongActivity::class.java).apply {
                                putExtra("_pos", position)
                                if (tabName == "喜欢的歌") {
                                    putExtra("_sort", "db_web_love")
                                } else {
                                    putExtra("_sort", "db_local")
                                }
                                startActivity(this)
                            }
                        }
                    }.create()
                arrRecyclerView!!.layoutManager = LinearLayoutManager(context)
            }
            codeColl -> {
                val arrAdapter = CommonRecyclerAdapter.Builder()
                arrRecyclerView!!.adapter = arrAdapter
                    .setData(musicCollectData!!).setLayout(R.layout.item_recycler_list)
                    .bindView { holder, innerData, position ->
                        val coll = innerData as MusicCreatorData.MusicList
                        holder.itemView.txtScanTitle_item.text = coll.title
                        holder.itemView.txtScanArtist_item.text = coll.artist
                        holder.itemView.txtScanTitle_item.setOnClickListener {
                            //myLog("$mTAG: position=$position")
                            Intent(activity, SongActivity::class.java).apply {
                                putExtra("_pos", position)
                                putExtra("_sort", "web_collect")
                                startActivity(this)
                            }
                        }
                    }.create()
                arrRecyclerView!!.layoutManager = LinearLayoutManager(context)
            }
            else -> {
                myLog("$mTAG: what=${it.what}")
            }
        }
        false
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        myLog("$mTAG: onCreated")
        try {
            val uid = myActReadIntSPF(this.activity, "spfUserId")
            if (tabName == "已传作品" && uid != null) {
                initWebData(uid)
            } else {
                beanArr = beanManager.getBeanArr(tabName == "喜欢的歌")
                val msg = Message()
                msg.what = codeDB
                arrHandler.sendMessage(msg)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //异步获取网络音频数据
    private fun initWebData(mid: Int) {
        val musicTask = CommonWebTask()
        musicTask.url = getApiMusicUidList(mid)
        musicTask.setCallbackHandler { innerData ->
            val data = Gson().fromJson(innerData, MusicCreatorData.MusicData::class.java)
            if (data.code == 20000) {
                musicCollectData = data.data
                FileOP().save(requireContext(), "musicColl.json", innerData)
                val msg = Message()
                msg.what = codeColl
                arrHandler.sendMessage(msg)
            } else {
                myLog("$mTAG: $innerData")
            }
        }
        musicTask.execute()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        val view: View = inflater.inflate(R.layout.fragment_music_child, container, false)
        arrRecyclerView = view.findViewById(R.id.recyclerViewMusic_musicChild)
        return view
    }
}